package org.tjc.net.manager.config.json;

import lombok.Data;
import org.tjc.net.manager.exception.ParseConfException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tjc
 * @description
 * @Date Created in 20:06 2020-12-20
 */
@Data
public class NgHttpModule extends NgModule {
    List<NgServerModule> servers = new ArrayList<>();

    public static ModuleSet ngSet = (ctx, conf) -> {
        NgHttpModule httpModule = new NgHttpModule();

        httpModule.setCtx(ctx);

        for (String key : conf.getKeys()) {
            if (!MetaNgCommand.contains(key)) {
                throw new ParseConfException("unexpect key: " + key);
            }
            MetaNgCommand subCmd = MetaNgCommand.get(key);
            if (subCmd.getType() == MetaNgCommand.CMD_MODULE) {
                Configuration subConf = conf.getConfiguration(key);
                subCmd.invoke(httpModule, subConf);
            } else if (subCmd.getType() == MetaNgCommand.CMD_LINE) {
                Object value = conf.get(key);
                subCmd.invoke(httpModule,key, value);
            }

        }
        ((NgMainModule) ctx).setHttp(httpModule);
    };

    public void addServer(NgServerModule conf) {
        servers.add(conf);
    }

    @Override
    public void init() {
        servers.stream().forEach(NgServerModule::init);
    }
}
